package com.gamota.mobi;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.gamota.mobi.adapter.DownloadItemView.DownloadSelectListener;
import com.gamota.mobi.adapter.DownloadingAdapter;
import com.gamota.mobi.download.DownloadManager;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.AlertDialogManager;


public class AllDownloadingActivity extends SherlockFragmentActivity implements
OnChildClickListener, OnItemClickListener, DownloadSelectListener,
OnClickListener, OnCancelListener{
	
	private static final String TAG = "DM";
	private ListView downloadingListView;
	private View mEmptyView;
	private DownloadManager mDownloadManager;
	private Cursor mSizeSortedCursor;
	private DownloadingAdapter adapter;
	private ViewGroup mSelectionMenuView;
	private ImageButton mSelectionDeleteButton;
	private ImageButton mSelectionButton;
	private ImageButton mCloseActionMenuButton;
	private MyContentObserver mContentObserver = new MyContentObserver();
	private MyDataSetObserver mDataSetObserver = new MyDataSetObserver();
	private int mStatusColumnId;
	private int mIdColumnId;
	private int mUriColumnId;
	private int mLocalUriColumnId;
	private int mReasonColumndId;
	private Button viewFullDownloadedFiles;
	
	private Long mQueuedDownloadId = null;
	private AlertDialog mQueuedDialog;

	private Set<Long> mSelectedIds = new HashSet<Long>();

	private class MyContentObserver extends ContentObserver {
		public MyContentObserver() {
			super(new Handler());
		}

		@Override
		public void onChange(boolean selfChange) {
			handleDownloadsChanged();
		}
	}

	private class MyDataSetObserver extends DataSetObserver {
		@Override
		public void onChanged() {
			// may need to switch to or from the empty view
			chooseListToShow();
		}
	}

	public void handleDownloadsChanged() {
		checkSelectionForDeletedEntries();

		if (mQueuedDownloadId != null && moveToDownload(mQueuedDownloadId)) {
			if (mSizeSortedCursor.getInt(mStatusColumnId) != DownloadManager.STATUS_PAUSED
					|| !isPausedForWifi(mSizeSortedCursor)) {
				mQueuedDialog.cancel();
			}
		}
	}

	private boolean moveToDownload(long downloadId) {
		for (mSizeSortedCursor.moveToFirst(); !mSizeSortedCursor.isAfterLast(); mSizeSortedCursor
				.moveToNext()) {
			if (mSizeSortedCursor.getLong(mIdColumnId) == downloadId) {
				return true;
			}
		}
		return false;
	}

	private boolean isPausedForWifi(Cursor cursor) {
		return cursor.getInt(mReasonColumndId) == DownloadManager.PAUSED_QUEUED_FOR_WIFI;
	}

	private void checkSelectionForDeletedEntries() {
		// gather all existing IDs...
		Set<Long> allIds = new HashSet<Long>();
		for (mSizeSortedCursor.moveToFirst(); !mSizeSortedCursor.isAfterLast(); mSizeSortedCursor.moveToNext()) {
			allIds.add(mSizeSortedCursor.getLong(mIdColumnId));
		}
		// ...and check if any selected IDs are now missing
		for (Iterator<Long> iterator = mSelectedIds.iterator(); iterator.hasNext();) {
			if (!allIds.contains(iterator.next())) {
				iterator.remove();
			}
		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		setContentView(R.layout.tab_downloading);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		initVariables();
		downloadingListView = (ListView) findViewById(R.id.list_downloading);
		downloadingListView.setOnItemClickListener(this);
		viewFullDownloadedFiles = (Button) findViewById(R.id.btn_view_full_downloaded_file);
		viewFullDownloadedFiles.setOnClickListener(this);
		mEmptyView = findViewById(R.id.empty);
		mSelectionMenuView = (ViewGroup) findViewById(R.id.action_menu);
		mSelectionDeleteButton = (ImageButton) findViewById(R.id.selection_delete);
		mSelectionDeleteButton.setOnClickListener(this);
		mSelectionButton = (ImageButton) findViewById(R.id.deselect_all);
		mSelectionButton.setOnClickListener(this);
		mCloseActionMenuButton = (ImageButton) findViewById(R.id.close_action_menu);
		mCloseActionMenuButton.setOnClickListener(this);
		downloadingListView.setAdapter(adapter);
		chooseListToShow();
	}

	@SuppressWarnings("deprecation")
	protected void initVariables() {
		// TODO Auto-generated method stub
		mDownloadManager = new DownloadManager(getContentResolver(), getPackageName());
		mDownloadManager.setAccessAllDownloads(false);
		DownloadManager.Query baseQuery = new DownloadManager.Query().setOnlyIncludeVisibleInDownloadsUi(true);
		mSizeSortedCursor = mDownloadManager.query(baseQuery.orderBy(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP, DownloadManager.Query.ORDER_DESCENDING));
		// only attach everything to the listbox if we can access the download
		// database. Otherwise,
		// just show it empty
		if (haveCursors()) {
			startManagingCursor(mSizeSortedCursor);
			mStatusColumnId = mSizeSortedCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
			mIdColumnId = mSizeSortedCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
			mUriColumnId = mSizeSortedCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
			mLocalUriColumnId = mSizeSortedCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
			mReasonColumndId = mSizeSortedCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
			adapter = new DownloadingAdapter(this, mSizeSortedCursor, this);
		}
	}
	
	private void showRunningDialog(long downloadId) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.download_running)
				.setMessage(R.string.dialog_running_body)
				.setNegativeButton(R.string.cancel_running_download,
						getDeleteClickHandler(downloadId))
				.setPositiveButton(R.string.pause_download,
						getPauseClickHandler(downloadId))
				.setNeutralButton(R.string.close, getCloseClickHandler()).show();
	}

	private void showPausedDialog(long downloadId) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.download_queued)
				.setMessage(R.string.dialog_paused_body)
				.setNegativeButton(R.string.delete_download,
						getDeleteClickHandler(downloadId))
				.setPositiveButton(R.string.resume_download,
						getResumeClickHandler(downloadId))
				.setNeutralButton(R.string.close, getCloseClickHandler()).show();
	}

	private void showFailedDialog(long downloadId, String dialogBody) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.dialog_title_not_available)
				.setMessage(dialogBody)
				.setNegativeButton(R.string.delete_download,
						getDeleteClickHandler(downloadId))
				.setPositiveButton(R.string.retry_download,
						getRestartClickHandler(downloadId))
				.setNeutralButton(R.string.close, getCloseClickHandler()).show();
	}

	private DialogInterface.OnClickListener getDeleteClickHandler(
			final long downloadId) {
		return new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				deleteDownload(downloadId);
				Intent i = new Intent(Constants.ACTION_CANCEL_DOWNLOAD);
				i.putExtra(Constants.DOWNLOAD_ID, downloadId);
				sendBroadcast(i);
			}
		};
	}

	/**
	 * @return an OnClickListener to pause the given downloadId from the
	 *         Download Manager
	 */
	private DialogInterface.OnClickListener getPauseClickHandler(
			final long downloadId) {
		return new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDownloadManager.pauseDownload(downloadId);
			}
		};
	}
	
	private DialogInterface.OnClickListener getCloseClickHandler() {
		return new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		};
	}

	/**
	 * @return an OnClickListener to resume the given downloadId from the
	 *         Download Manager
	 */
	private DialogInterface.OnClickListener getResumeClickHandler(
			final long downloadId) {
		return new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDownloadManager.resumeDownload(downloadId);
			}
		};
	}

	/**
	 * @return an OnClickListener to restart the given downloadId in the
	 *         Download Manager
	 */
	private DialogInterface.OnClickListener getRestartClickHandler(
			final long downloadId) {
		return new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDownloadManager.restartDownload(downloadId);
			}
		};
	}

	private void deleteDownload(long downloadId) {
		if (moveToDownload(downloadId)) {
			int status = mSizeSortedCursor.getInt(mStatusColumnId);
			boolean isComplete = status == DownloadManager.STATUS_SUCCESSFUL|| status == DownloadManager.STATUS_FAILED;
			String localUri = mSizeSortedCursor.getString(mLocalUriColumnId);
			if (isComplete && localUri != null) {
				String path = Uri.parse(localUri).getPath();
				if (path.startsWith(Environment.getExternalStorageDirectory().getPath())) {
					mDownloadManager.markRowDeleted(downloadId);
					Intent cancel = new Intent(Constants.ACTION_CANCEL_DOWNLOAD);
					cancel.putExtra(Constants.DOWNLOAD_ITEM, downloadId);
					sendBroadcast(cancel);
					return;
				}
			}
		}
		mDownloadManager.remove(downloadId);
	}

	private void handleItemClick(Cursor cursor) {
		long id = cursor.getInt(mIdColumnId);
		switch (cursor.getInt(mStatusColumnId)) {
		case DownloadManager.STATUS_PENDING:
		case DownloadManager.STATUS_RUNNING:
			showRunningDialog(id);
			break;

		case DownloadManager.STATUS_PAUSED:
			if (isPausedForWifi(cursor)) {
				mQueuedDownloadId = id;
				mQueuedDialog = new AlertDialog.Builder(this)
						.setTitle(R.string.dialog_title_queued_body)
						.setMessage(R.string.dialog_queued_body)
						.setPositiveButton(R.string.keep_queued_download, null)
						.setNegativeButton(R.string.remove_download,
								getDeleteClickHandler(id))
						.setOnCancelListener(this).show();
			} else {
				showPausedDialog(id);
			}
			break;

		case DownloadManager.STATUS_SUCCESSFUL:
			openCurrentDownload(cursor);
			break;

		case DownloadManager.STATUS_FAILED:
			showFailedDialog(id, getErrorMessage(cursor));
			break;
		}
	}

	private String getUnknownErrorMessage() {
		return getString(R.string.dialog_failed_body);
	}

	private boolean isOnExternalStorage(Cursor cursor) {
		String localUriString = cursor.getString(mLocalUriColumnId);
		if (localUriString == null) {
			return false;
		}
		Uri localUri = Uri.parse(localUriString);
		if (!localUri.getScheme().equals("file")) {
			return false;
		}
		String path = localUri.getPath();
		String externalRoot = Environment.getExternalStorageDirectory()
				.getPath();
		return path.startsWith(externalRoot);
	}

	private String getErrorMessage(Cursor cursor) {
		switch (cursor.getInt(mReasonColumndId)) {
		case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
			if (isOnExternalStorage(cursor)) {
				return getString(R.string.dialog_file_already_exists);
			} else {
				// the download manager should always find a free filename for
				// cache downloads,
				// so this indicates a strange internal error
				return getUnknownErrorMessage();
			}

		case DownloadManager.ERROR_INSUFFICIENT_SPACE:
			if (isOnExternalStorage(cursor)) {
				return getString(R.string.dialog_insufficient_space_on_external);
			} else {
				return getString(R.string.dialog_insufficient_space_on_cache);
			}

		case DownloadManager.ERROR_DEVICE_NOT_FOUND:
			return getString(R.string.dialog_media_not_found);

		case DownloadManager.ERROR_CANNOT_RESUME:
			return getString(R.string.dialog_cannot_resume);

		default:
			return getUnknownErrorMessage();
		}
	}

	private void openCurrentDownload(Cursor cursor) {
		Uri localUri = Uri.parse(cursor.getString(mLocalUriColumnId));
		try {
			getContentResolver().openFileDescriptor(localUri, "r").close();
		} catch (FileNotFoundException exc) {
			Log.d(TAG, "Failed to open download " + cursor.getLong(mIdColumnId), exc);
			showFailedDialog(cursor.getLong(mIdColumnId), getString(R.string.dialog_file_missing_body));
			return;
		} catch (IOException exc) {
			// close() failed, not a problem
		}
		String mimeType = cursor.getString(mUriColumnId).substring(cursor.getString(mUriColumnId).lastIndexOf(".") + 1, cursor.getString(mUriColumnId).length());
		if(mimeType.equalsIgnoreCase("apk")){
			Utils.installAPK(this, cursor.getString(mLocalUriColumnId));
		} else if(mimeType.equalsIgnoreCase("epub")){
			openEbook(cursor.getString(mLocalUriColumnId));
		} else if(mimeType.equalsIgnoreCase("zip")){
			openComic(cursor.getString(mLocalUriColumnId));
		}
	}
	
	public void openEbook(String path){
		if(Utils.checkCoolReader(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/epub+zip");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_ebook_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(AllDownloadingActivity.this);
					String items[] = {"Cool Reader"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							Intent i = new Intent(AllDownloadingActivity.this, ItemBrokerActivity.class);
							i.putExtra(Constants.STORE_KEY, "apps");
							i.putExtra(Constants.PREVIOUS_SCREEN, "manage");
							i.putExtra(Constants.SLUG, "cooldreader");
							i.putExtra(Constants.KEY_REFERER, "direct");
							startActivity(i);
						}
					});
				}
			});
		}
	}
	
	private void openComic(String path){
		if(Utils.checkDroidComicViewer(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/x-acv");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_comic_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(AllDownloadingActivity.this);
					String items[] = {"Droid Comic Viewer"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							Intent i = new Intent(AllDownloadingActivity.this, ItemBrokerActivity.class);
							switch (pos) {
							case 0:
								i.putExtra(Constants.SLUG, Utils.ACV_SLUG);
								i.putExtra(Constants.KEY_REFERER, "direct");
								i.putExtra(Constants.STORE_KEY, "apps");
								i.putExtra(Constants.PREVIOUS_SCREEN, "manage");
								startActivity(i);
								break;
							}
						}
					});
				}
			});
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (haveCursors()) {
			mSizeSortedCursor.registerContentObserver(mContentObserver);
			mSizeSortedCursor.registerDataSetObserver(mDataSetObserver);
			refresh();
		}
	}

	@SuppressWarnings("deprecation")
	private void refresh() {
		mSizeSortedCursor.requery();
		// Adapters get notification of changes and update automatically
	}

	@Override
	public void onPause() {
		super.onPause();
		if (haveCursors()) {
			mSizeSortedCursor.unregisterContentObserver(mContentObserver);
			mSizeSortedCursor.unregisterDataSetObserver(mDataSetObserver);
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private boolean haveCursors() {
		return mSizeSortedCursor != null;
	}

	private void chooseListToShow() {
		downloadingListView.setVisibility(View.GONE);
		if(mSizeSortedCursor == null || mSizeSortedCursor.getCount() == 0){
			mEmptyView.setVisibility(View.VISIBLE);
		} else {
			mEmptyView.setVisibility(View.GONE);
			activeListView().setVisibility(View.VISIBLE);
			activeListView().invalidateViews(); // ensure checkboxes get updated
		}
	}

	private void showOrHideSelectionMenu() {
		boolean shouldBeVisible = !mSelectedIds.isEmpty();
		boolean isVisible = mSelectionMenuView.getVisibility() == View.VISIBLE;
		if (shouldBeVisible) {
			updateSelectionMenu();
			if (!isVisible) {
				// show menu
				mSelectionMenuView.setVisibility(View.VISIBLE);
				mSelectionMenuView.startAnimation(AnimationUtils.loadAnimation(
						this, R.anim.footer_appear));
			}
		} else if (!shouldBeVisible && isVisible) {
			// hide menu
			mSelectionMenuView.setVisibility(View.GONE);
			mSelectionMenuView.startAnimation(AnimationUtils.loadAnimation(
					this, R.anim.footer_disappear));
		}
		//adapter.notifyDataSetChanged();
	}

	private void updateSelectionMenu() {
		@SuppressWarnings("unused")
		int deleteButtonStringId = R.string.delete_download;
		if (mSelectedIds.size() == 1) {
			Cursor cursor = mDownloadManager.query(new DownloadManager.Query().setFilterById(mSelectedIds.iterator().next()));
			try {
				cursor.moveToFirst();
				switch (cursor.getInt(mStatusColumnId)) {
				case DownloadManager.STATUS_FAILED:
					deleteButtonStringId = R.string.delete_download;
					break;

				case DownloadManager.STATUS_PENDING:
					deleteButtonStringId = R.string.remove_download;
					break;

				case DownloadManager.STATUS_PAUSED:
				case DownloadManager.STATUS_RUNNING:
					deleteButtonStringId = R.string.cancel_running_download;
					break;
				}
			} finally {
				cursor.close();
			}
		}
		//mSelectionDeleteButton.setText(deleteButtonStringId);
	}

	/**
	 * @return the ListView that should currently be visible.
	 */
	private ListView activeListView() {
		return downloadingListView;
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		mQueuedDownloadId = null;
		mQueuedDialog = null;
	}

	private void clearSelection() {
		mSelectedIds.clear();
		showOrHideSelectionMenu();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLongArray("selection", getSelectionAsArray());
	}

	private long[] getSelectionAsArray() {
		long[] selectedIds = new long[mSelectedIds.size()];
		Iterator<Long> iterator = mSelectedIds.iterator();
		for (int i = 0; i < selectedIds.length; i++) {
			selectedIds[i] = iterator.next();
		}
		return selectedIds;
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		if(savedInstanceState != null){
			mSelectedIds.clear();
			for (long selectedId : savedInstanceState.getLongArray("selection")) {
				mSelectedIds.add(selectedId);
			}
			chooseListToShow();
			showOrHideSelectionMenu();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.selection_delete:
			Intent i;
			for (Long downloadId : mSelectedIds) {
				deleteDownload(downloadId);
				i = new Intent(Constants.ACTION_CANCEL_DOWNLOAD);
				i.putExtra(Constants.DOWNLOAD_ID, downloadId);
				sendBroadcast(i);
			}
			clearSelection();
			break;
		case R.id.deselect_all:
			if (mSizeSortedCursor.moveToFirst()) {
		        do {
		        	mSelectedIds.add(mSizeSortedCursor.getLong(mIdColumnId));
		        } while (mSizeSortedCursor.moveToNext());
		    }
			//adapter.notifyDataSetChanged();
			break;
		case R.id.close_action_menu:
			clearSelection();
			break;
		case R.id.btn_view_full_downloaded_file:
			i = new Intent(AllDownloadingActivity.this, DownloadedFileManagerActivity.class);
			startActivity(i);
			break;
		}
	}

	@Override
	public void onDownloadSelectionChanged(long downloadId, boolean isSelected) {
		// TODO Auto-generated method stub
		if (isSelected) {
			mSelectedIds.add(downloadId);
		} else {
			mSelectedIds.remove(downloadId);
		}
		showOrHideSelectionMenu();
	}

	@Override
	public boolean isDownloadSelected(long id) {
		// TODO Auto-generated method stub
		return mSelectedIds.contains(id);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		mSizeSortedCursor.moveToPosition(position);
		handleItemClick(mSizeSortedCursor);
	}

	@Override
	public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
			int arg3, long arg4) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
//			Intent i = new Intent(this, HomeActivity.class);
//			i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			startActivity(i);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onBackPressed(){
//		Intent i = new Intent(this, HomeActivity.class);
//		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		startActivity(i);
//		finish();
		super.onBackPressed();
	}
}
